package com.ssm.redis.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

    //springboot操作Redis默认为jdk的序列化方式,会出现乱码。我们要重写redisTemplate自定义序列化方式。

    //重写要指定泛型类型<key为String, value为任意类型>
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        RedisSerializer<String> redisSerializer = new StringRedisSerializer(); //定义Redis序列化工具对象

        //添加redisConnectionFactory
        redisTemplate.setConnectionFactory(redisConnectionFactory);

        //key固定就是String类型，所以序列化时可直接用redisSerializer
        redisTemplate.setKeySerializer(redisSerializer); //配置默认类型(String)序列化
        redisTemplate.setHashKeySerializer(redisSerializer); // //配置Hash类型序列化

        //value可能为任意类型，所以使用jackson序列化工具
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer());
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer());
        return redisTemplate;
    }

    private Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer() {
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);

        //对jackson序列化(set)和反序列化(get)进行配置
        ObjectMapper objectMapper = new ObjectMapper();

        //setVisibility用于设置对象的可见性规则，即序列化和反序列化时哪些属性应该被包含或排除
        //参数一:它定义了要设置可见性的属性访问器类型，可以是FIELD（设置字段的可见性）、GETTER（设置getter方法的可见性）或它们的组合。
        //参数二:它定义了属性的可见性级别，可以是ANY（任何级别的属性都可见）、NONE（没有属性可见）或其他更具体的级别。
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);

        //反序列化(get)时,遇到未知属性会不会报错  序列化为set
        //true - 遇到没有的属性就报错 false - 没有的属性不会管，不会报错
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
        return jackson2JsonRedisSerializer;
    }
}
